<?php

namespace app\api\service;
use addons\epay\library\Service;
use app\admin\model\CouponRecord;
use app\admin\model\User;
use app\common\model\Advance;
use app\common\model\Goodorder;
use app\common\model\Occupants;
use app\common\model\Pauserecords;
use app\common\model\Payment;
use app\common\model\Reservations;
use app\common\model\Rooms;
use app\common\model\Upgraderules;
use think\Db;

error_reporting(E_ERROR);
class OrderService
{
    //计算花了多少钱
    public function order_money($id){

        $pauseRecords = Db::table('fa_pause_records')
            ->where('occupant_id', $id)
            ->select();
        $totalPauseDuration = 0; // 初始化总时长


        foreach ($pauseRecords as $record) {
            if ($record['resume_time'] !== null) {
                $totalPauseDuration += ($record['resume_time'] - $record['pause_time']);
            } else {
                $totalPauseDuration += (time() - $record['pause_time']); // 当前时间减去暂停时间
            }
        }

        $info = Occupants::where('id',$id)->find();
        if($info['status']==0){
            $hour=ceil((time()-$info['join_time']-$info['gift_time']-$totalPauseDuration)/60);
        }else{
            $hour=ceil(($info['leave_time']-$info['join_time']-$info['gift_time']-$totalPauseDuration)/60);
        }
        if($hour<0){
            $hour=0;
        }

        //游玩金额
        $yw_mony=$hour*($info['unit_price']/60);
        //点单金额
        $good_tatal=Goodorder::where('occupants_id',$id)->sum('total');
        return ['yw_money'=>round($yw_mony,1),'good_tatal'=>$good_tatal];

    }



    //计算暂停了多久
    public function totalPauseDuration($id,$now_time){
        $pauseRecords = Db::table('fa_pause_records')
            ->where('occupant_id', $id)
            ->select();
        $totalPauseDuration = 0; // 初始化总时长


        foreach ($pauseRecords as $record) {
            if ($record['resume_time'] !== null) {
                $totalPauseDuration += ($record['resume_time'] - $record['pause_time']);
            } else {
                $totalPauseDuration += ($now_time - $record['pause_time']); // 当前时间减去暂停时间
            }
        }
        return $totalPauseDuration;
    }

     function loadCoupon($params)
    {
        if (empty($params['coupon_record_id'])) {
            return;
        }
        if (!is_numeric($params['coupon_record_id'])) {
            fail('优惠券ID格式错误');
        }

        $coupon_record_id = intval($params['coupon_record_id']);
        if ($coupon_record_id) {
            $couponRecord = CouponRecord::get($coupon_record_id, ['coupon']);
            if (!$couponRecord) {
                fail("优惠券记录不存在");
            }
            if ($couponRecord['user_id'] != $params['user_id']) {
                fail("优惠券记录非当前用户所有 - ");
            }

            if ($couponRecord['status'] != 0) {
                fail("优惠券已使用或已过期");
            }
            if ($couponRecord['coupon']['start_time'] > time()) {
                fail("优惠券未到使用时间");
            }
            if ($couponRecord['coupon']['end_time'] < time()) {
                fail("优惠券已过期");
            }

            if ($couponRecord['min_money'] > $params['amount']) {
                fail("优惠券不满足使用条件");
            }
            $discount = min($params['amount'], $couponRecord['money']);
            $this->fields['coupon_id'] = $couponRecord['coupon_id'];
            $this->fields['coupon_record_id'] = $couponRecord['id'];
            $this->fields['coupon_discount'] = $discount;
        }
        return $this->fields;
    }


    public static function reservation_payment($id,$uid)
    {
        $order=Reservations::where('id','=', $id)->find();
        if (!$order) {
            fail('订单不存在');
        }
        if ($order['deposit_status'] != 0) {
            fail('订单状态错误');
        }
        $user_info = User::where('id','=',$uid)->find();
        if (!$user_info || !$user_info['openid']) {
            fail('用户信息不存在，或未绑定微信，请重新登录后再试');
        }
        return \addons\epay\library\Service::submitOrder($order['final_amount'], $order['order_no'], "wechat",'支付押金', request()->domain() . '/api/notify/reservation_pay', "", "miniapp",$user_info['openid']);
    }


    /**
     * 结算
     * @return mixed
     */
    public static function order_Payment($id,$uid,$title)
    {
        $order=Payment::where('id','=', $id)->find();
        if (!$order) {
            fail('订单不存在');
        }
        if ($order['pay_status'] != 0) {
            fail('订单状态错误');
        }
        $user_info = User::where('id','=',$uid)->find();
        if (!$user_info || !$user_info['openid']) {
            fail('用户信息不存在，或未绑定微信，请重新登录后再试');
        }
        return \addons\epay\library\Service::submitOrder($order['paid'], $order['order_no'], "wechat",'结算', request()->domain() . '/api/notify/order_pay', "", "miniapp",$user_info['openid']);
    }


    /*
     * 支付成功后
     */
    public function order_success($id)
    {

        $payment = Payment::where('id', $id)->find();
        if ($payment['pay_status'] == 1) {
            fail('该订单已支付');
        }
        $result = Payment::where('id', $id)->where('pay_status', 0)->update(['pay_status' => 1,'pay_time'=>time()]);
        if ($result == 0) {
            fail('该订单已支付');
        }
        $user=User::where('id',$payment['user_id'])->find();
        if($payment['method']=='月卡'){
            if($user['month_card']<=0){
                fail('月卡数量不足');
            }
            User::where('id',$user['id'])->setDec('month_card');
        }
            if($payment['balance']>0){
                \app\common\model\User::money(-$payment['balance'],$payment['user_id'],'消费-桌游');
            }
            //如果押金有剩余 退款
            if ($payment['left_money'] > 0) {
                if ($payment['reservations_id'] != null) {
                    $Reservations = Reservations::where('id', $payment['reservations_id'])->find();
                    // 获取预约支付的余额
                    $current_balance = $Reservations['balance_deduction'];

                    // 先判断用户的余额是否足够
                    if ($current_balance >= $payment['left_money']) {
                        // 如果余额足够，直接扣除指定的金额
                        \app\common\model\User::money($payment['left_money'], $payment['user_id'], '押金剩余退款');
                    } else {
                        // 如果余额不足，先扣除当前的余额
                        \app\common\model\User::money($current_balance, $payment['user_id'], '押金剩余退款');

                        // 计算剩余需要退款的金额
                        $refund_amount = $payment['left_money'] - $current_balance;

                        // 调用微信退款的逻辑，将剩余金额退还给用户
                        if ($refund_amount > 0) {
                            // 这里假设有一个退款的方法，您可能需要根据实际的业务逻辑替换这部分代码
                            $order = new Service();
                            $result = $order->refund(order_no(), $Reservations['order_no'], $Reservations['final_amount'] * 100, $refund_amount * 100);
                            if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') {
                                fail($result['err_code_des']);
                            }
                        }
                    }
                }
            }

        //结束代付用户的订单状态
        $advance = Advance::where('payment_id', $id)->select();
        $room_id = 0;
        foreach ($advance as $item) {
            $Occupants = Occupants::where('id', $item['order_id'])->find();
            $room_id = $Occupants['room_id'];
            if ($Occupants['leave_time'] == null) {
                $Occupants::where('id', $item['order_id'])->update(['status' => 2, 'leave_time' => time()]);
            } else {
                $Occupants::where('id', $item['order_id'])->update(['status' => 2]);
            }
            Advance::where('id', $item->id)->update(['pay_status' => 1]);

            //升级
            $this->up($Occupants['user_id']);

            //判断有没有没结束的暂停
            $pauseRecords = Db::table('fa_pause_records')
                ->where('occupant_id', $item['order_id'])
                ->where('status',1)
                ->select();
            foreach ($pauseRecords as $records) {
                $time = time();
                Pauserecords::where('id', $records['id'])->update(['status' => 2, 'resume_time' => $time]);
                Occupants::where('id',  $Occupants['id'])->update(['pause_status' => 1, 'pause_time' =>$Occupants['pause_time']+ ($time - $records['pause_time'])]);
            }

        }
        //房间没人的话 桌子变成空闲
        $in_count = Occupants::where('room_id', $room_id)->where('status', 0)->count();
        if ($in_count == 0) {
            Rooms::where('id', $room_id)->update(['status' => 0]);
        }
        //如果是预约的单子 预约状态改成结束
        if ($payment['reservations_id'] != null) {
          Reservations::where('id', $payment['reservations_id'])->update(['reservation_status'=>2]);
        }
    }


        //升级
    public function up($user_id){
        $occupants= Occupants::where('user_id',$user_id)->where('status',2)->field('leave_time,join_time')->select();
        $hour=0;
        foreach ($occupants as $item) {
            $hour+=ceil(($item['leave_time']-$item['join_time'])/3600);
        }
        $Upgraderules= Upgraderules::where('minutes','<=',$hour)->order('minutes desc')->find();
        if($Upgraderules){
            \app\admin\model\User::where('id',$user_id)->update(['level_id'=>$Upgraderules['id']]);
        }
    }

}